package com.lg.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lg.common.exception.GlobalException;
import com.lg.utils.R;

@Aspect
@Component
public class ValidatorInterceptor {

	  /** 
	* @Description: 环绕通知拦截controller 层校验参数
	* @param @param pjp
	* @param @param bindingResult
	* @param @return
	* @param @throws Throwable  
	* @return Object 
	* @throws 
	*/ 
	  @Around("execution(* com.lg..controller.*.*(..)) && args(..,bindingResult)")
      public Object doAround(ProceedingJoinPoint pjp, BindingResult bindingResult) throws Throwable {
          Object retVal;
          if (bindingResult.hasErrors()) {
              retVal = doErrorHandle(bindingResult);
          } else {
              retVal = pjp.proceed();
          }
          return retVal;
      }
	  
	  @ResponseBody
	  private Object doErrorHandle(BindingResult bindingResult){
	      StringBuffer sb = new StringBuffer();
		  for (ObjectError error : bindingResult.getAllErrors()) {
			  sb.append(error.getDefaultMessage()+"</br>");
          }
		  throw new GlobalException(R.error(sb.toString()));
	  }
}
